<script setup>
import { ref,onMounted,onUpdated,nextTick,computed,watch  } from 'vue';
import { SearchIcon,
    ChatMessageIcon,
    EllipsisIcon,
    BacktopIcon,
    FileCopyIcon,
    File1Icon} from 'tdesign-icons-vue-next';
import {Delete,Document} from '@element-plus/icons-vue';
import { useUserStore,userWebStore } from '@/stores'
import axios from 'axios'
import { MessagePlugin } from 'tdesign-vue-next';
const userStore = useUserStore()
const userWeb = userWebStore()



const is_top = ref(true)
const textarea = ref('')
const chatList = ref([])
//websocket对象
let ws = null;
//当前对话框，对方用户ID

//好友列表（在数据查）
const friendlist = ref([])
//
const online = ref(null);
const chatWindow = ref(null)

const sendmessage = ref({
    message: null,
    toName: 0,
    flag:0,
})
const newMessage = ref('');  
const scrollToBottom = async () => {  
    await nextTick();
    chatWindow.value.scrollTop = chatWindow.value.scrollHeight;  
};  

onMounted(() => {
    getFriendList()
    scrollToBottom(); // 确保在组件加载时滚动到底部
    ws = new WebSocket("ws://localhost:8000/user/chat/" + userStore.user.id);
    ws.onopen = onOpen;
    ws.onmessage = onMessage;
    ws.onclose = onClose;
    choose(userWeb.otherInfo.id)
}); 

const onOpen = () => {
    online.value = true;
}
const onClose = () => {
    online.value = false;
}

const onMessage = (evt) => {
    //获取服务端推送过来的消息
    const dataStr = evt.data;
    //将dataStr 转换为json对象
    const res = JSON.parse(dataStr);
    //判断是否是系统消息
    if (res.system) {
        //系统消息  好友列表展示
        userWeb.setOnline(res.message)
        
    } else {
        //非系统消息
        const otherId = res.fromName;
        if(otherId == userWeb.otherInfo.id){
            if(res.flag == 0){
                chatList.value.push({ownId: userWeb.otherInfo.id,text : res.message,flag : 0})
            }
            else if(res.flag == 3){
                chatList.value.push({ownId: userWeb.otherInfo.id,text : res.message,flag : 3})
            }
            
        }
    }
}


const getFriendList = () => {
    axios.post('http://localhost:8000/user/chat/friend',{},{
        headers: {
            authentication: userStore.token,
        }
    }).then(resp => {
        if(resp.data.code === 1){
            console.log(resp.data)
            friendlist.value = resp.data.data;
            userWeb.setFriend(resp.data.data)
        }
    });
    
}

watch(chatList, (newVal, oldVal) => {  
    scrollToBottom();  
}, { deep: true });
//发送消息
const sendMessage = () => {
    console.log(newMessage.value)
    if (newMessage.value && newMessage.value !== '') { 
        newMessage.value = newMessage.value.replace(/\n/g, '<br>');
        chatList.value.push({ownId:userStore.user.id, 'text': newMessage.value, 'flag': 1});
        sendOther(0)
        newMessage.value = '';
        scrollToBottom();
    }  
};
const sendOther = (x) => {
    sendmessage.value.message = newMessage.value;
    sendmessage.value.toName = userWeb.otherInfo.id;
    sendmessage.value.flag = x;
    ws.send(JSON.stringify(sendmessage.value))
}
//绑定键盘按键
const handleKeyDown = (event) => {
    if (event.ctrlKey && event.key === 'Enter') {  
        event.preventDefault(); // 阻止默认的换行行为（如果有的话）  
        newMessage.value += '\n'; // 插入换行符
    } else if (event.key === 'Enter' && !event.ctrlKey) { 
        event.preventDefault();  
        sendMessage();  
    }
};     
const sendPhone = () => {
    newMessage.value = phone;
    sendMessage()
}
const sendVx = () => {
    newMessage.value = vx;
    sendMessage()
}
const sendBio = () => {
    newMessage.value = userStore.user.userBio
    chatList.value.push({ownId: userStore.user.id,'text': userStore.user.userBio,'flag': 2});
    sendOther(3)
    newMessage.value = ''
    scrollToBottom();
}
const phone = '这是我的电话：'+ userStore.user.phone;

const vx = '这是我的微信：'+userStore.user.userVx;
const autosizeOptions = ref({  
  minRows: 6,  
  maxRows: 6
}); 

const choose = (id) => {
    axios.get('http://localhost:8000/user/chat/info',{
        params:{
            id,
        },headers: {
            authentication: userStore.token,
        }
    }).then(resp => {
        if(resp.data.code === 1){
            userWeb.setOtherInfo(resp.data.data)
            chatList.value = resp.data.data.history;
        }
    })
}

const lookBio = (url) => {
    window.open("https://view.xdocin.com/view?src=" + encodeURIComponent(url))
}

const backList = () => {
    showList.value = 0;
    choose(userWeb.otherInfo.id)
}
const value = ref('');
const showList = ref(0);
const addFriendList = ref(null)
const check_form = () => {
    if(value.value === ''){
        MessagePlugin.warning('请输入用户名再进行查找！')
    }else{
        show_Friends()
    }
}
const show_Friends = () => {
    axios.get('http://localhost:8000/user/chat/addfriend',{
        params:{
            username: value.value
        },headers: {
            authentication: userStore.token,
        }
    }).then(resp => {
        if(resp.data.code === 1){

            if(resp.data.data.length > 0){
                addFriendList.value = resp.data.data;
                showList.value = 1;
            }else{
                showList.value = 2;
            }
        }else{
            MessagePlugin.warning(resp.data.msg)
        }
    }).catch(error => {
        MessagePlugin.error(error.data.msg)
    })
}
const choose_send = (id) => {
    choose(id)
    showList.value = 0
}
const build_chat = (id) => {
    axios.get('http://localhost:8000/user/chat/buildchat',{
        params:{
            id,
        },headers: {
            authentication: userStore.token,
        }
    }).then(resp => {
        if(resp.data.code === 1){
            MessagePlugin.success("添加成功！")
            getFriendList();
            showList.value = 0;
        }else{
            MessagePlugin.warning(resp.data.msg)
        }
    })
}
const replace = (x) => {
    if(x === '' || x === null){
        return '';
    }
    return x.replace(/<br>/g, ' ');
}
const deleteList = (id) => {
    axios.get('http://localhost:8000/user/chat/delete',{
        params:{
            id,
        },headers: {
            authentication: userStore.token,
        }
    }).then(resp => {
        if(resp.data.code === 1){
            MessagePlugin.success("删除成功！")
            getFriendList();
            userWeb.removeInfo()
        }
    })
}
</script>

<template>
                                
    <div class="chat">
        <t-card class="chat-1">
            <t-input v-model="value" class="select-1"  placeholder="添加好友，请输入用户名"/>
            <el-button @click="check_form" style="margin-left: 15px;margin-bottom: 20px;"> 
                <SearchIcon style="margin-right: 8px;"/>
                搜索
            </el-button>
            <div class="list-left" style="height: 740px;">
                <div v-if="showList === 2">
                    <div>
                        <el-button @click="backList">返回好友列表</el-button>
                    </div>
                    <div style="text-align: center;margin-top: 40px;color: #999999;">
                    抱歉没有查到哦！请换个搜索词吧！
                    </div>
                </div>
                <!-- ---------------------------------------- -->
                <div v-if="showList === 1">
                    <div>
                        <el-button @click="backList">返回好友列表</el-button>
                    </div>
                    <div class="show-friend" v-for="(x,index) in addFriendList" :key="index">
                        <div style="display: flex;">
                            <img style="float: left; width: 53px;height: 53px;border-radius: 50%;" :src=x.avatar alt="">
                            <div style="display: inline-block;">
                                <div style="display: flex; margin-bottom: 6px;">
                                    <div style="font-size: 15px; width: 177px;float: left;">{{x.username}}</div>
                                    <div  v-if="userWeb.onlineList[x.id] === 0" style="float: left;
                                    color: #40B14F;font-weight: 500;font-size: 13px;border-radius: 4px;
                                    width: 40px;height: 22px;padding: 0px 7px;background-color: #E1F5E3;">
                                    <div style="display: inline-block; width: 7px;height: 7px;border-radius: 50%;background-color: #3AC249"></div>
                                    在线</div>
                                    <!-- <div style=" width: 40px; float: left;">在线</div> -->
                                </div>
                                <div style="color: #999999;">注册时间：{{x.createTime}}</div>
                            </div>
                        </div>
                        <div style="display: flex;margin-top: 10px;">
                            <el-button v-if="userWeb.friendList[x.id] !== 0" @click="build_chat(x.id)" style="margin-left: auto; " type="primary">加好友</el-button>
                            <el-button v-if="userWeb.friendList[x.id] === 0" @click="choose_send(x.id)"  style="margin-left: auto; " type="success">发消息</el-button>
                        </div>
                    </div>
                </div>
                
                <!-- ------------------------------------------- -->
                <div  v-if="showList === 0" @click="choose(x.id)" v-for="(x, index) in friendlist" :key="index" class="flag">
                    <div style="display: flex;">
                        <img :src=x.logo style="float: left;border-radius: 50%;  width: 50px; height: 50px;"></img>
                        <div style="float: left;margin-top: 3px;">
                            <div style=" width: 236px;display: flex;">
                                <div style="width: 145px; display: flex;align-items: flex-start; float: left;">
                                
                                    <div class="text" style="font-size: 13px;
                                    margin-left: 8px;width: 80px;
                                    flex-shrink: 0;">{{x.name}}</div>
                                    <div class="text" style="font-size: 12px;
                                    color: #666666;
                                    margin-left: 5px;">{{x.bossJob}}</div>
                                
                                </div>
                                <div  v-if="userWeb.onlineList[x.id] === 0" style="float: left;
                                color: #40B14F;font-weight: 500;font-size: 13px;border-radius: 4px;
                                width: 38px;height: 22px;padding: 0px 7px;background-color: #E1F5E3;">
                                <div style="display: inline-block; width: 7px;height: 7px;border-radius: 50%;background-color: #3AC249"></div>
                                在线</div>
                                <div class="right" style="float: left; font-size: 13px;">{{x.lastTime}}</div>
                            </div>
                        <div style="color: #999999;
                        margin-left: 8px;
                        float: left;
                        width: 196px;
                        font-size: 12px;
                        margin-top: 3px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;">{{replace(x.content)}}</div>
                        
                        <t-popup placement="top-right" style="display: inline-block;">
                        <div  variant="outline"><EllipsisIcon /></div>
                            <!-- <div slot="content">触发元素是指触发浮层内容显示的元素</div> -->
                            <template #content>
                            <div class="icon"><BacktopIcon style="margin-right: 7px;margin-left: 5px;"/>顶置</div>
                            <div @click="deleteList(x.id)" class="icon"><el-icon style="margin-right: 7px;
                            margin-left: 5px;
                            position: relative;top: 2px;"><Delete /></el-icon>删除</div>
                            </template>
                        </t-popup>
                        </div>
                    </div>

                    <div style="margin-top: 6px;color: #666666;font-family: 黑体;">{{x.company}}</div>
                </div>
            </div>
            
        </t-card>
        <t-card class="chat-2">
            <div style=" display: flex;
             align-items: center;box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.19);
             padding-left: 10px;
             margin-bottom: 10px;
             height: 50px;">
                <div class="text-top" style="float: left;">{{userWeb.otherInfo.username}}</div>
                <div class="text-top" style="float: left;">{{userWeb.otherInfo.company}}</div>
                <div class="text-top" style="display: inline-block;">{{userWeb.otherInfo.bossJob}}</div>
                <el-button v-if="is_top" class="right" style="margin-right: 10px;">取消顶置</el-button>
                <el-button v-else style="margin-left: 410px;">顶置</el-button>
            </div>
            <div ref="chatWindow" class="list-left" style="height: 510px;width: 780px; margin-bottom: 10px;
            " >
                <div style="margin-top: 20px;margin-bottom: 20px;  width: 750px;" v-for="(x, index) in chatList" :key="index">
                    <div class="message other" >
                        <img v-if="x.flag === 0" style="margin-right: 5px; width: 32px;height: 32px; border-radius: 50%;" :src=userWeb.otherInfo.avatar  alt="">
                        <span class="text" v-if="x.flag === 0" v-html="x.text"></span>
                        
                    </div>

                    <div class="message own" >
                        <span class="text" v-if="x.flag === 1" v-html="x.text"></span>
                        <img v-if="x.flag === 1" style="margin-left: 5px; width: 32px;height: 32px; border-radius: 50%;" :src=userStore.user.avatar  alt="">
                    </div>

                    <div class="message other" >
                        <img v-if="x.flag === 3" style="margin-right: 5px; width: 32px;height: 32px; border-radius: 50%;" :src=userWeb.otherInfo.avatar  alt="">
                        <div style=" width: 280px;height: 140px; display: inline-block;" class="bio" v-if="x.flag === 3" >
                            <div style="height: 90px; display: flex;align-items: center;">
                                <div style="float: left; border-radius: 5px; width: 45px;height: 45px;background-color: rgb(39, 148, 211)">
                                    <el-icon><Document style="transform: scale(2);
                                    color: white;position: relative ;left: 15px;top: 11px;"/></el-icon>
                                </div>
                                <div style="margin-left: 48px;font-size: 15px;">
                                    个人简历.pdf
                                </div>
                            </div>
                            <el-button @click="lookBio(x.text)" style="background-color: rgb(218, 236, 248);
                            border-radius: 6px;width: 270px;height: 40px;">查看附件简历</el-button>
                        </div>
                        
                    </div>

                    <div class="message own" >
                        <div style=" width: 280px;height: 140px; display: inline-block;" class="bio" v-if="x.flag === 2" >
                            <div style="height: 90px; display: flex;align-items: center;">
                                <div style="float: left; border-radius: 5px; width: 45px;height: 45px;background-color: rgb(39, 148, 211)">
                                    <el-icon><Document style="transform: scale(2);
                                    color: white;position: relative ;left: 15px;top: 11px;"/></el-icon>
                                </div>
                                <div style="margin-left: 48px;font-size: 15px;">
                                    个人简历.pdf
                                </div>
                            </div>
                            <el-button @click="lookBio(x.text)" style="background-color: rgb(218, 236, 248);
                            border-radius: 6px;width: 270px;height: 40px;">查看附件简历</el-button>
                        </div>
                        <img v-if="x.flag === 2" style="margin-left: 5px; width: 32px;height: 32px; border-radius: 50%;" :src=userStore.user.avatar  alt="">
                    </div>
                </div>
            </div>
            <el-divider style="margin: 0px !important;"/>
            <div style="height: 190px;margin-top: 10px;">
                <div style="margin-bottom: 5px; display: flex;">
                    <el-button @click="sendBio">发简历</el-button>
                    <el-button @click="sendPhone">发电话</el-button>
                    <el-button @click="sendVx">发微信</el-button>
                    <el-button @click="sendMessage" class="right" type="primary">发送</el-button>
                </div>
                <el-input
                    @keydown="handleKeyDown"
                    v-model="newMessage"
                    style="width: 100%; border: none !important;outline: none;"
                    :autosize="autosizeOptions"
                    type="textarea"
                    placeholder="请输入"
                    resize="none"
                    
                />
                <div style="font-size: 13px;color: #7b7b7b;padding-right: 20px;text-align: right;">按Enter键发送，按Ctrl+Enter键换行</div>
            </div>
        </t-card>
    </div>
</template>

<style scoped>
.chat{
    padding-top: 20px;
    padding-bottom: 10px;
    display: flex;
    justify-content: center;
    background: linear-gradient(to bottom, rgb(189, 222, 241) 30%, white 100%);
}
.chat-1{
    float: left;
    width: 350px;
    height: 817px;

}
.chat-2{
    display: inline-block;
    width: 820px;
    height: 817px;
    margin-left: 7px;
}
.select-1{
    width: 200px;
    float: left;
    margin-bottom: 20px;
}
.text{
    float: left;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.flag{
    margin: 8px 0px;
    height: 77px;
    padding: 11px 5px;
    cursor: pointer;
}
.flag:hover{
    background-color: #f7f5f5;
    border-radius: 10px;
    
}
.icon{
    width: 70px;
    height: 23px;
    padding: 5px;
    border-radius: 7px;
    cursor: pointer;
}
.icon:hover{
    background-color: #f9f7f7;
}
.list-left {  
    overflow-y: scroll;
    box-sizing: border-box; 
}  
  
/* 尝试美化滚动条，但这种方法主要在WebKit浏览器中有效 */  
.list-left::-webkit-scrollbar {  
    width: 4px; /* 滚动条的宽度 */  
}  
  
.list-left::-webkit-scrollbar-track {  
    background:#FFFFFF;
}  
  
.list-left::-webkit-scrollbar-thumb {  
    background: rgb(189, 222, 241); /* 滚动条的滑块背景色 */  
    border-radius: 10px;
}  
.text-top{
    font-size: 14px;
    margin: 0px 10px;
    color: #666666;
}
.right{
    margin-left: auto;
}

/* /---------------------- */
.message {  
    display: flex;  
    align-items: flex-start; /* 文本垂直对齐方式 */  
    margin-bottom: 10px; /* 消息之间的间距 */  
    clear: both; /* 清除浮动，确保消息不会堆叠 */  
}  
  
.message .text {  
    padding: 5px 10px; /* 文本内边距 */  
    border-radius: 5px; /* 圆角 */  
    max-width: 80%; /* 限制文本宽度，防止过长 */  
    word-wrap: break-word; /* 单词换行 */  
    /* 注意：不需要设置 text-align，因为 span 元素默认是左对齐的 */  
}  
  
.message.own {  
    justify-content: flex-end; /* 让自己发送的消息靠右 */  
}  
  
.message.own .text {  
    background-color: #b2e281; /* 自己发送的消息背景色 */  
    color: #000; /* 文本颜色 */  
    /* 不需要额外的对齐设置，因为 span 默认左对齐 */  
}  
  
.message.other {  
    justify-content: flex-start; /* 让别人发送的消息靠左（这是默认值，但为了明确性可以加上） */  
}  
  
.message.other .text {  
    background-color: #eee; /* 别人发送的消息背景色 */  
    color: #000; /* 文本颜色 */  
    /* 同样不需要额外的对齐设置 */  

}
.bio{
    background: linear-gradient(to bottom, rgb(216, 237, 248) 1%, white 100%);
    color: #000; /* 文本颜色 */  

    padding: 5px 10px; /* 文本内边距 */  
    border-radius: 10px; /* 圆角 */  
    max-width: 80%; /* 限制文本宽度，防止过长 */  
    word-wrap: break-word; /* 单词换行 */

    border: 1px rgb(74, 169, 223) solid;
}
.show-friend{
    margin: 8px 0px;
    border-radius: 10px;
    padding: 11px 10px;
    background: linear-gradient(to bottom, rgb(212, 237, 251) 1%, rgb(244, 240, 240) 100%);
}
</style>